package com.lsl.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lsl.dto.UserDTO;
import com.lsl.entity.FollowingUser;
import com.lsl.feign.AccountFeignClient;
import com.lsl.mapper.FollowingUserMapper;
import com.lsl.service.FollowingUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class FollowingUserServiceImpl extends ServiceImpl<FollowingUserMapper, FollowingUser> implements FollowingUserService {

    @Autowired
    private AccountFeignClient accountFeignClient;

    @Override
    @Transactional
    public boolean followUser(Integer userId, Integer followingUserId) {
        FollowingUser following = new FollowingUser();
        following.setUserId(userId);
        following.setFollowingUserId(followingUserId);
        return save(following);
    }

    @Override
    @Transactional
    public boolean unfollowUser(Integer userId, Integer followingUserId) {
        return lambdaUpdate()
            .eq(FollowingUser::getUserId, userId)
            .eq(FollowingUser::getFollowingUserId, followingUserId)
            .remove();
    }

    @Override
    public boolean isFollowing(Integer userId, Integer followingUserId) {
        return lambdaQuery()
            .eq(FollowingUser::getUserId, userId)
            .eq(FollowingUser::getFollowingUserId, followingUserId)
            .count() > 0;
    }

    @Override
    public List<UserDTO> getFollowingUsers(Integer userId) {
        List<Integer> followingIds = lambdaQuery()
            .eq(FollowingUser::getUserId, userId)
            .list()
            .stream()
            .map(FollowingUser::getFollowingUserId)
            .collect(Collectors.toList());
        if (followingIds.isEmpty()) {
            return null;
        }
        return accountFeignClient.getUsersByIds(followingIds);
    }

    @Override
    public List<UserDTO> getFollowers(Integer userId) {
        List<Integer> followerIds = lambdaQuery()
            .eq(FollowingUser::getFollowingUserId, userId)
            .list()
            .stream()
            .map(FollowingUser::getUserId)
            .collect(Collectors.toList());
        if (followerIds.isEmpty()) {
            return null;
        }
        return accountFeignClient.getUsersByIds(followerIds);
    }
    
}
